//import 'dart:html';

import 'package:flutter/material.dart';
import 'package:gzx_dropdown_menu/gzx_dropdown_menu.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:magic_car/zhanshi/cheyuandetail.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:cached_network_image/cached_network_image.dart';

class SortCondition {
  String name;
  bool isSelected;
  String tag;

  SortCondition({this.name, this.isSelected, this.tag});
}

class GZXDropDownMenuTestPage extends StatefulWidget {
  @override
  _GZXDropDownMenuTestPageState createState() =>
      _GZXDropDownMenuTestPageState();
}

class _GZXDropDownMenuTestPageState extends State<GZXDropDownMenuTestPage> {
  int page = 1;
  List car = [];
  // List<String> _dropDownHeaderItemStrings = ['类型', '品牌', '价格', '筛选'];
  List<String> _dropDownHeaderItemStrings = ['品牌', '车型', '价格'];
  List<SortCondition> _brandSortConditions = [];
  List<SortCondition> _distanceSortConditions = [];
  SortCondition _selectBrandSortCondition;
  SortCondition _selectDistanceSortCondition;
  GZXDropdownMenuController _dropdownMenuController =
      GZXDropdownMenuController();

  var _scaffoldKey = new GlobalKey<ScaffoldState>();
  GlobalKey _stackKey = GlobalKey();

  List BrandList = new List();
  List secondList = new List();
  String brand = "";
  String cartype = "";
  String price = "";
  @override
  void initState() {
    super.initState();

    _brandSortConditions.add(SortCondition(name: '全部', isSelected: true));
    _brandSortConditions.add(SortCondition(name: '轿车', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '两厢轿车', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '面包车', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '跑车', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '皮卡', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '三厢轿车', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '商务车/MPV', isSelected: false));
    _brandSortConditions.add(SortCondition(name: 'SUV/越野车', isSelected: false));

    _selectBrandSortCondition = _brandSortConditions[0];

    // _distanceSortConditions.add(SortCondition(name: '距离近', isSelected: true));
    _distanceSortConditions
        .add(SortCondition(name: '价格由低至高', isSelected: false, tag: "0"));
    _distanceSortConditions
        .add(SortCondition(name: '价格由高至低', isSelected: false, tag: "1"));
    _distanceSortConditions
        .add(SortCondition(name: '5万以下', isSelected: false, tag: "0-5"));
    _distanceSortConditions
        .add(SortCondition(name: '5万-10万', isSelected: false, tag: "5-10"));
    _distanceSortConditions
        .add(SortCondition(name: '10万-20万', isSelected: false, tag: "10-20"));
    _distanceSortConditions
        .add(SortCondition(name: '20万-30万', isSelected: false, tag: "20-30"));
    _distanceSortConditions
        .add(SortCondition(name: '30万-50万', isSelected: false, tag: "30-50"));
    _distanceSortConditions
        .add(SortCondition(name: '50万以上', isSelected: false, tag: "50-10000"));

    _selectDistanceSortCondition = _distanceSortConditions[0];
    loaddata();
    loadBrand();
  }

  loadBrand() {
    Map<String, String> map = new Map();

    HttpHelper.post(HttpHelper.API_Brand, (data) async {
      //loadpage.close();
      if (data != null) {
        print(data);
        //Toast.show(data["msg"], context);

        if (data["code"].toString() == "1") {
          List temp = data["info"];

          setState(() {
            BrandList = temp;
            //  hotList = hotList;
            //  loaddata=true;
          });
        }
      }
    }, params: map);
  }

  loaddata() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    Map<String, String> map = new Map();
    map["page"] = this.page.toString();
    map["brand"] = this.brand;
    map["cartype"] = this.cartype;
    map["price"] = this.price;
  
    HttpHelper.post(HttpHelper.ApI_CarList, (data) async {
      //loadpage.close();
      if (data != null) {
        print(data);
        //Toast.show(data["msg"], context);

        if (data["code"].toString() == "1") {
          var info = data["info"];
          setState(() {
            // status = info["status"].toString();
            car = info;
          });
        }
      }
    }, params: map);
  }

  @override
  Widget build(BuildContext context) {
    print('_GZXDropDownMenuTestPageState.build');

    return Scaffold(
      key: _scaffoldKey,
      appBar: PreferredSize(
          child: AppBar(
            backgroundColor: Color.fromRGBO(7, 169, 251, 1),
            elevation: 0,
          ),
          preferredSize: Size.fromHeight(0)),
      backgroundColor: Colors.white,
      endDrawer: Container(
        margin: EdgeInsets.only(
            left: MediaQuery.of(context).size.width / 4, top: 0),
        color: Colors.white,
//        child: Container(color: Colors.red,child: Padding(
//          padding: const EdgeInsets.all(8.0),
//          child: TextField(),
//        ),),
        child: ListView(
          children: <Widget>[TextField()],
        ),
      ),
      body: Stack(
        key: _stackKey,
        children: <Widget>[
          Column(
            children: <Widget>[
              Container(
                width: MediaQuery.of(context).size.width,
                height: 60,
                // color: Color.fromRGBO(7, 169, 251, 1),
                color: Color.fromRGBO(7, 169, 251, 1),
                alignment: Alignment.center,
                child: Text(
                  '车源展示',
                  style: TextStyle(
                    fontSize: 16,
                    color: Colors.white,
                  ),
                ),
              ),
//              SizedBox(height: 20,),
              // 下拉菜单头部
              GZXDropDownHeader(
                // 下拉的头部项，目前每一项，只能自定义显示的文字、图标、图标大小修改
                items: [
                  GZXDropDownHeaderItem(_dropDownHeaderItemStrings[0]),
                  GZXDropDownHeaderItem(_dropDownHeaderItemStrings[1]),
                  GZXDropDownHeaderItem(_dropDownHeaderItemStrings[2]),
                  // GZXDropDownHeaderItem(_dropDownHeaderItemStrings[3],
                  //     iconData: Icons.filter_frames, iconSize: 18),
                ],
                // GZXDropDownHeader对应第一父级Stack的key
                stackKey: _stackKey,
                // controller用于控制menu的显示或隐藏
                controller: _dropdownMenuController,
                // 当点击头部项的事件，在这里可以进行页面跳转或openEndDrawer
                onItemTap: (index) {
                  //控制展现方式
                  // if (index == 3) {
                  //   _scaffoldKey.currentState.openEndDrawer();
                  // }
                },
//                // 头部的高度
//                height: 40,
//                // 头部背景颜色
//                color: Colors.red,
//                // 头部边框宽度
//                borderWidth: 1,
//                // 头部边框颜色
//                borderColor: Color(0xFFeeede6),
//                // 分割线高度
//                dividerHeight: 20,
//                // 分割线颜色
//                dividerColor: Color(0xFFeeede6),
//                // 文字样式
//                style: TextStyle(color: Color(0xFF666666), fontSize: 13),
//                // 下拉时文字样式
//                dropDownStyle: TextStyle(
//                  fontSize: 13,
//                  color: Theme.of(context).primaryColor,
//                ),
//                // ���标大小
//                iconSize: 20,
//                // 图标颜色
//                iconColor: Color(0xFFafada7),
//                // 下拉时图标颜色
//                iconDropDownColor: Theme.of(context).primaryColor,
              ),
              Expanded(
                child: ListView.separated(
                    itemCount: car.length,
                    separatorBuilder: (BuildContext context, int index) =>
                        Divider(height: 1.0),
                    itemBuilder: (BuildContext context, int index) {
                      return Padding(
                        padding: new EdgeInsets.fromLTRB(10, 10, 10, 0),
                        child: new Container(
                            

                            child: GestureDetector(
                                behavior: HitTestBehavior.opaque,
                                onTap: () {
                                  Navigator.push(
                                    context,
                                    new MaterialPageRoute(
                                        builder: (context) =>
                                            new CardetailPage(car[index])),
                                  );
                                },
                                child: new Row(
                                  children: <Widget>[
                                    Expanded(
                                        flex: 1,
                                        child: 
                                        (
                                          new Container(
                                            height: 50,width: 50,
                                            child:Image.network(car[index]["car_thumb"]
                                                 [0],fit: BoxFit.contain,),
                                          // CachedNetworkImage(
                                          //   width: 150,height: 100,
                                          //   imageUrl: car[index]["car_thumb"]
                                          //       [0],
                                          //   imageBuilder: (context,
                                          //           imageProvider) =>
                                          //       Container(
                                          //           decoration: BoxDecoration(
                                                      
                                          //         image: DecorationImage(
                                          //             image: imageProvider,
                                          //             fit: BoxFit.contain
                                          //             // colorFilter:
                                          //             //     ColorFilter.mode(Colors.red, BlendMode.colorBurn)
                                          //             ),
                                          //       )))
                                          )
                                        // new Image.network(
                                        //   car[index]["car_thumb"][0],

                                        // ),
                                        )),
                                    Expanded(
                                      flex: 2,
                                      child: new Column(
                                        children: <Widget>[
                                          new Container(
                                            
                                            alignment: Alignment.topLeft,
                                            child: new Padding(
                                                padding:
                                                    new EdgeInsets.fromLTRB(
                                                        10, 0, 0, 0),
                                                child: Text(
                                                  car[index]["title"],
                                                  style: TextStyle(
                                                      color: Color.fromRGBO(
                                                          16, 29, 55, 1),
                                                      fontSize: 15),
                                                )),
                                          ),
                                          new Padding(
                                            padding: new EdgeInsets.fromLTRB(
                                                10, 8, 0, 0),
                                            child: new Row(
                                              crossAxisAlignment: CrossAxisAlignment.start,
                                              mainAxisAlignment: MainAxisAlignment.start,
                                              children: <Widget>[
                                                
                                               Image.asset('resource/images/baoxiu/inspected.png',width: 15,height:17),
                                               Padding(padding: new EdgeInsets.fromLTRB(5,0,0,0),child:
                                               Text('已检测',style: TextStyle(fontSize:11,color: Color.fromRGBO(212,35,122,1),))),
                                               car[index]["is_guratee"].toString()=="1"?
                                               Padding(padding: new EdgeInsets.fromLTRB(15,0,0,0),child:
                                               Image.asset('resource/images/baoxiu/guarateed.png',width: 15,height:17)):Container(height:0),
                                               car[index]["is_guratee"].toString()=="1"?
                                               Padding(padding: new EdgeInsets.fromLTRB(5,0,0,0),child:
                                               Text('已保修',style: TextStyle(fontSize:11,color: Color.fromRGBO(18,150,219,1),))):Container(height:0)
                                                

                                                
                                              ],
                                            ),
                                          ),

                                          new Padding(
                                            padding: new EdgeInsets.fromLTRB(
                                                10, 5, 0, 10),
                                            child: new Row(
                                              children: <Widget>[
                                                Expanded(
                                                  flex: 1,
                                                  child: Text(
                                                    '¥' +
                                                        car[index]["car_price"]
                                                            .toString() +
                                                        "万",
                                                    style: TextStyle(
                                                        color: Color.fromRGBO(255,99,71, 1),
                                                        fontSize: 16),
                                                  ),
                                                ),
                                                Expanded(
                                                    flex: 1,
                                                    child: Container(
                                                      height: 25,
                                                      child: FlatButton(
                                                        onPressed: () {
                                                          Navigator.push(
                                                            context,
                                                            new MaterialPageRoute(
                                                                builder: (context) =>
                                                                    new CardetailPage(
                                                                        car[index])),
                                                          );
                                                          // print(index.toString());
                                                        },
                                                        child: Text(
                                                          '发布求购',
                                                          style: TextStyle(
                                                              color:
                                                                  Colors.white,fontSize: 13),
                                                        ),
                                                      ),
                                                      decoration: BoxDecoration(
                                                        image: DecorationImage(
                                                          image: AssetImage(
                                                              "resource/images/zhanshi/round.png"),
                                                          fit: BoxFit.fitHeight,
                                                        ),
                                                      ),
                                                    ))
                                              ],
                                            ),
                                          )
                                        ],
                                      ),
                                    )
                                  ],
                                ))),
                      );
                    }),
              ),
            ],
          ),
          // 下拉菜单
          GZXDropDownMenu(
            // controller用于控制menu的显示或隐藏
            controller: _dropdownMenuController,
            // 下拉菜单显示或隐藏动画时长
            animationMilliseconds: 100,
            // 下拉菜单，高度自定义，你想显示什么就显示什么，完全由你决定，你只需要在选择后调用_dropdownMenuController.hide();即可
            menus: [
              GZXDropdownMenuBuilder(
                  dropDownHeight: 40 * 8.0,
                  dropDownWidget: _buildAddressWidget((selectValue) {
                    _dropDownHeaderItemStrings[0] = selectValue;
                    _dropdownMenuController.hide();
                    setState(() {});
                  })),
              GZXDropdownMenuBuilder(
                  dropDownHeight: 40 * 8.0,
                  dropDownWidget:
                      _buildConditionListWidget(_brandSortConditions, (value) {
                    _selectBrandSortCondition = value;
                    _dropDownHeaderItemStrings[1] =
                        _selectBrandSortCondition.name == '全部'
                            ? '车型'
                            : _selectBrandSortCondition.name;
                    _dropdownMenuController.hide();
                    setState(() {});
                  })),
              GZXDropdownMenuBuilder(
                  dropDownHeight: 40.0 * _distanceSortConditions.length,
                  dropDownWidget:
                      _buildPriceListWidget(_distanceSortConditions, (value) {
                    _selectDistanceSortCondition = value;
                    _dropDownHeaderItemStrings[2] =
                        _selectDistanceSortCondition.name;
                    _dropdownMenuController.hide();
                    setState(() {});
                  })),
            ],
          ),
        ],
      ),
    );
  }

  int _selectTempFirstLevelIndex = 0;
  int _selectFirstLevelIndex = 0;
  int _selectSecondLevelIndex = -1;

  _buildAddressWidget(void itemOnTap(String selectValue)) {
//    List firstLevels = new List<int>.filled(15, 0);
    List firstLevels = new List<String>.generate(BrandList.length+1, (int index) {
      if (index == 0) {
        return '全部';
      }
      return BrandList[index-1]['title'];
    });

    print(_selectTempFirstLevelIndex.toString());

    List secondLevels = _selectTempFirstLevelIndex > 0
        ? new List<String>.generate(
            BrandList[_selectTempFirstLevelIndex-1]['child'].length, (int index) {
            if (_selectTempFirstLevelIndex == 0) {
              return '';
            }
            return BrandList[_selectTempFirstLevelIndex-1]['child'][index]
                ["name"];
          })
        : [];

    return Row(
      children: <Widget>[
        Container(
          width: 100,
          child: ListView(
            children: firstLevels.map((item) {
              int index = firstLevels.indexOf(item);
              return GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  //if(_selectTempFirstLevelIndex == 0)return;
                  _selectTempFirstLevelIndex = index;
                  print('点击一级');

                  if(index==0){
                    
                    //. _dropdownMenuController.hide();
                     setState(() {
                       brand='';
                       
                     });
                     loaddata();
                    
                  }

                  if (_selectTempFirstLevelIndex == 0) {
                    itemOnTap('全部');
                    return;//点击全部直接返回
                  }
                  setState(() {
                    _selectFirstLevelIndex= index;
                  });
                },
                child: Container(
                    height: 40,
                    color: _selectTempFirstLevelIndex == index
                        ? Colors.grey[200]
                        : Colors.white,
                    alignment: Alignment.center,
                    child: _selectTempFirstLevelIndex == index
                        ? Text(
                            '$item',
                            style: TextStyle(
                              color: Colors.blue,
                            ),
                          )
                        : Text('$item')),
              );
            }).toList(),
          ),
        ),
        Expanded(
          child: Container(
            color: Colors.grey[200],
            child: ListView(
              children: secondLevels.map((item) {
                int index = secondLevels.indexOf(item);
                return GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () {
                      print('二级选项');
                      print(BrandList[_selectFirstLevelIndex-1]['child'][index]);
                      setState(() {
                        brand = BrandList[_selectFirstLevelIndex-1]['child']
                            [index]['id'];
                      });
                      _selectSecondLevelIndex = index;
                      _selectFirstLevelIndex = _selectTempFirstLevelIndex;
                      itemOnTap(item);
                      loaddata(); //加载数据
                      // if (_selectSecondLevelIndex == 0) {
                      //   itemOnTap(firstLevels[_selectFirstLevelIndex]);
                      // } else {
                      //   itemOnTap(item);
                      // }
                    },
                    child: Container(
                      height: 40,
                      alignment: Alignment.centerLeft,
                      child: Row(children: <Widget>[
                        SizedBox(
                          width: 50,
                        ),
                        _selectFirstLevelIndex == _selectTempFirstLevelIndex &&
                                _selectSecondLevelIndex == index
                            ? Text(
                                '$item',
                                style: TextStyle(
                                  color: Colors.blue,
                                ),
                              )
                            : Text('$item'),
                      ]),
                    ));
              }).toList(),
            ),
          ),
        )
      ],
    );
  }

  _buildConditionListWidget(
      items, void itemOnTap(SortCondition sortCondition)) {
    return ListView.separated(
      shrinkWrap: true,
      scrollDirection: Axis.vertical,
      itemCount: items.length,
      // item 的个数
      separatorBuilder: (BuildContext context, int index) =>
          Divider(height: 1.0),
      // 添加分割线
      itemBuilder: (BuildContext context, int index) {
        SortCondition goodsSortCondition = items[index];
        return GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () {
            print('点击车型' + goodsSortCondition.name);
            setState(() {
              cartype = goodsSortCondition.name;
            });
            for (var value in items) {
              value.isSelected = false;
            }
            goodsSortCondition.isSelected = true;

            itemOnTap(goodsSortCondition);
            loaddata();
          },
          child: Container(
//            color: Colors.blue,
            height: 40,
            child: Row(
              children: <Widget>[
                SizedBox(
                  width: 16,
                ),
                Expanded(
                  child: Text(
                    goodsSortCondition.name,
                    style: TextStyle(
                      color: goodsSortCondition.isSelected
                          ? Colors.blue
                          : Colors.black,
                    ),
                  ),
                ),
                goodsSortCondition.isSelected
                    ? Icon(
                        Icons.check,
                        color: Colors.blue,
                        size: 16,
                      )
                    : SizedBox(),
                SizedBox(
                  width: 16,
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  _buildPriceListWidget(items, void itemOnTap(SortCondition sortCondition)) {
    return ListView.separated(
      shrinkWrap: true,
      scrollDirection: Axis.vertical,
      itemCount: items.length,
      // item 的个数
      separatorBuilder: (BuildContext context, int index) =>
          Divider(height: 1.0),
      // 添加分割线
      itemBuilder: (BuildContext context, int index) {
        SortCondition goodsSortCondition = items[index];
        return GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () {
            print('点击价格' + goodsSortCondition.name);
            setState(() {
              price = goodsSortCondition.tag;
            });
            for (var value in items) {
              value.isSelected = false;
            }
            goodsSortCondition.isSelected = true;

            itemOnTap(goodsSortCondition);
            loaddata();
          },
          child: Container(
//            color: Colors.blue,
            height: 40,
            child: Row(
              children: <Widget>[
                SizedBox(
                  width: 16,
                ),
                Expanded(
                  child: Text(
                    goodsSortCondition.name,
                    style: TextStyle(
                      color: goodsSortCondition.isSelected
                          ? Colors.blue
                          : Colors.black,
                    ),
                  ),
                ),
                goodsSortCondition.isSelected
                    ? Icon(
                        Icons.check,
                        color: Colors.blue,
                        size: 16,
                      )
                    : SizedBox(),
                SizedBox(
                  width: 16,
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
